require("../less/register.less");

document.ready(function() {
    //保存真实验证码
    let trueCode = "";
    //验证码
    let captcha1 = new CaptchaMini();
    captcha1.draw(document.querySelector('#captcha1'), r => {
        // console.log(r, '验证码1');
        trueCode = r;
    });

    //表单验证
    let phone = document.querySelector('#phone');
    let code = document.querySelector('#code');
    let pwd1 = document.querySelector('#pwd1');
    let pwd2 = document.querySelector('#pwd2');
    let regBtn = document.querySelector('#regBtn');
    let errMsg = document.querySelector('#errMsg');

    regBtn.addEventListener('click', function() {
        errMsg.style.display = 'block';
        //手机号
        let phoneVal = phone.value;
        if (!phoneVal) {
            errMsg.textContent = '手机号不能为空';
            return;
        }
        if (!/^1[3456789]\d{9}$/.test(phoneVal)) {
            errMsg.textContent = '手机号格式错误';
            return;
        }
        //验证码 不区分大小写
        let codeVal = code.value;
        if (!codeVal) {
            errMsg.textContent = '验证码不能为空';
            return;
        }
        if (codeVal.toLowerCase() != trueCode.toLowerCase()) {
            errMsg.textContent = '验证码不正确';
            return;
        }
        //密码
        let pwd1Val = pwd1.value;
        let pwd2Val = pwd2.value;
        if (!pwd1Val) {
            errMsg.textContent = '密码不能为空';
            return;
        }
        if (!/[\w]{6,12}$/.test(pwd1Val)) {
            errMsg.textContent = '密码格式错误';
            return;
        }
        if (pwd1Val !== pwd2Val) {
            errMsg.textContent = '两次密码不一致';
            return;
        }

        errMsg.style.display = 'none';
        errMsg.textContent = '';

        //调用注册接口,实现真正的注册(与后端结合)
        axios.post("http://139.9.177.51:8099/users/add", { account: phoneVal, password: pwd1Val })
            .then(function(res) {
                if (res.data.status == 0) {
                    window.tipsFn('注册成功', res.data.status);
                    let timeId = setTimeout(function() {
                        location.href = './login.html'
                    }, 1000)
                } else {
                    window.tipsFn('用户已存在', res.data.status);
                }
            })
            .catch(function(err) {
                console.log(err);
            })
    })

    //跳转登录界面
    let jumpLogin = document.querySelector('#jumpLogin');
    jumpLogin.addEventListener('click', function() {
        location.href = './login.html';
    })





})